<?php
defined('IN_XLP') or exit('Access Denied');

class appAction extends commonAction {

    private $config; //首页整体配置

    private $service;//服务中心
    private $tab;    //标签页（栏目）
    private $module; //模块

    private $mongo;

    function __construct() {
        parent::__construct();
        parent::_checkLogin();

        $this->config  = C('app/index');
        $this->tab     = $this->config['layout'];
        $this->module  = $this->config['module'];
        $this->service = F('steward/service_city_'.admin::$adminInfo['city_id']);
        if(!$this->service) {
            $this->service = M('ste_service')
                ->field('`sid`,`stitle`')
                ->where(array('city_id'=>admin::$adminInfo['city_id']))
                ->findAll(false);
        }

        T('db/mogo');
        $config = C("app/db");
        $config = $config['mongodb'];
        $this->mongo = new mogo($config['host'].':'.$config['port'], $config['db']);
    }

    /*
     * app首页配置
     */
    public function index() {
        if(isset($_POST['module'])) {
            $this->save();
        }

        $this->assign('tab', $this->tab);
        $this->display();
    }

    public function get_data() {

        $layout_id = $this->_getid('layout');

        $data = $this->mongo->find("index", array("layout_id"=>$layout_id));

        //按位置排序
        uasort($data, function($x, $y){
            return ($x['order']>$y['order']);
        });

        if($data && is_array($data)) {
            foreach ($data as $k => $v) {
                //服务社
                foreach ($data[$k]['service'] as $key => $value) {
                    $data[$k]['service'][$key] = $this->service[$value]['stitle'];
                }
                //位置
                $data[$k]['order'] = $this->config['floor'][$layout_id][$v['order']];
                //类别
                $data[$k]['mode'] = $this->module[$v['mode']];
                //图片
                $data[$k]['image'] = empty($v['image']) ? "" : getImgUrl($v['image']);
                //起始时间
                $data[$k]['starttime'] = $v['starttime']>0 ? date('Y-m-d H:i:s', $v['starttime']) : '';
                $data[$k]['endtime']   = $v['endtime']>0 ? date('Y-m-d H:i:s', $v['endtime']) : '';
            }
        }

        $this->JsonReturn('ok', $data, 1);
    }

    /*
     * 添加接口内容
     */
    public function add() {
        $id = $this->_getid('id');  //栏目id

        $this->pictureConfig(); //图片设置
        $this->floorConfig($id);    //各层布局位置
        $this->assign('id', $id);   //栏目id
        $this->assign('topic', $this->tab[$id]['name']);  //栏目名称
        $this->assign('service', $this->service);   //各服务中心
        $this->assign('module', $this->module); //各调用模块
        $this->display();
    }

    /*
     * 编辑接口内容
     */
    public function edit() {
        $id = $this->_get('id');
        $data = $this->mongo->find( "index", array('_id'=>new MongoId($id)) );

        $layout_id = $data[$id]['layout_id'];

        $_id = (string)$data[$id]['_id'];
        if(!empty($data[$_id]['image'])) {
            $data[$_id]['image'] = getImgUrl($data[$_id]['image']);
        }
        $this->assign('_id', $_id);
        $this->assign('data', $data[$_id]);
        
        $this->pictureConfig(); //图片设置
        $this->floorConfig($layout_id);    //各层布局位置
        $this->assign('id', $layout_id);   //栏目id
        $this->assign('topic', $this->tab[$layout_id]['name']);  //栏目名称
        $this->assign('service', $this->service);   //各服务中心
        $this->assign('module', $this->module); //各调用模块
        $this->display();
    }

    /*
     * 保存数据
     */
    private function save() {

        $data = array();

        $data['service'] = array(); //服务中心
        foreach ($_POST['service'] as $k => $v) {
            $data['service'][] = (int)$v;
        }

        $data['mode']      = $this->_post('module', 0); //调用模块
        $data['order']     = $this->_postid('position');//内容位置
        $data['title']     = $this->_post('title', 0); //内容标题
        $data['para']      = empty($_POST['para']) ? null : strip_tags($_POST['para']); //参数
        $data['starttime'] = empty($_POST['starttime']) ? 0 : strtotime($_POST['starttime']);   //开始时间
        $data['endtime']   = empty($_POST['endtime']) ? 0 : strtotime($_POST['endtime']);   //结束时间

        if($_POST['has_pic']) {
            $result = $this->upload();
            if($result['state']=='SUCCESS') {
                $data['image'] = $result['url'];
            } else {
                saveLog('app/content', $result['state']);
                showError('上传图片失败：'.$result['state']);
            }
        }

        //按照布局类型保存相应的数据格式
        $layout = $this->_postid('layout');
        $layout_name = $this->tab[$layout]['key'];

        $data['layout_id'] = $layout;
        $data['layout']    = $layout_name;

        //商品楼层
        if($layout_name == 'counter') {
            $data['color'] = $this->_post('color');
        }

        $_id = $this->_post('_id', '');
        if($_id) {
            $this->mongo->update("index", array("_id"=>new MongoId($_id)), $data);
        } else {
            $this->mongo->insert("index", $data);
        }
    }

    /*
     * 删除数据
     */
    public function del() {
        $id = $this->_get('id');
        $t  = $this->_get('t', "index");
        if($id) {
            $_id = new MongoId($id);
        } else {
            showError('无效参数');
        }
        $this->mongo->delete($t, array("_id"=>$_id));
        $this->JsonReturn('ok', 1, 1);
    }

    /*
     * 图片相关参数
     */
    private function pictureConfig() {
        $img_type = str_replace('|', ',', C('upload', 'pic_type'));
        $this->assign('img_type', $img_type);
    }

    /*
     * 各层位置布局
     */
    private function floorConfig($id=0) {
        $floor_cfg = $this->config['floor'];
        $this->assign('position', $floor_cfg[$id]);
    }

    /*
     * 图片上传
     */
    private function upload() {
        load('upload');
        $myUpload = new Myupload();
        $upload   = $myUpload->upload('app/city' . admin::$adminInfo['city_id']);
        // $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
        if ($upload) {
            $upload = $upload[0];
            if ($upload) {
                return array(
                    'url'      => $upload['savepath'],
                    'fileType' => $upload['type'],
                    'original' => $upload['realname'],
                    'state'    => 'SUCCESS',
                );
            } else {
                return array(
                    'url'      => '',
                    'fileType' => '',
                    'original' => '',
                    'state'    => $myUpload->getErrorMsg(),
                );
            }
        }
    }


    public function forum() {

        $page = $this->_getid("page", 1);
        $data = $this->mongo->find("forum");
        
        $total = count($data);
        $data  = array_slice($data, ($page-1)*10, 10);

        if($data) {
            foreach ($data as $k => $v) {
                $data[$k]['id']   = $k;
                $data[$k]['time'] = empty($v['time']) ? "" : date('Y-m-d H:i:s', $v['time']);
            }
        }

        $this->assign("msg_list", $data);
        $this->assign("total", $total);
        $this->assign("page", $page);
        $this->display();
    }

    public function forum_add() {
        if($_POST) {
            $data = array();
            $data['title'] = $this->_post('title');
            $data['mode']  = $this->_post('mode');
            $data['para']  = $this->_post('para');
            $data['time']  = strtotime($_POST['time']);

            $res = $this->mongo->insert("forum", $data);
            $this->JsonReturn("添加成功", 1, 1);
        }

        $this->display();
    }

    public function forum_edit() {
        if(isset($_POST['id'])) {

            $_id = $this->_post('id');

            $data = array();
            $data['title'] = $this->_post('title');
            $data['mode']  = $this->_post('mode');
            $data['para']  = $this->_post('para');
            $data['time']  = strtotime($_POST['time']);

            $this->mongo->update("forum", array("_id"=>new MongoId($_id)), $data);
            $this->JsonReturn("编辑成功", 1, 1);
        }

        $id = $this->_get("id");
        $data = $this->mongo->find("forum", array('_id'=>new MongoId($id)));
        if($data) {
            $data[$id]['time'] = date('Y-m-d H:i:s', $data[$id]['time']);
            $data[$id]['id'] = $id;
        } else {
            showError("没有查询到数据");
        }
        $this->assign("data", $data[$id]);
        $this->display();
    }

}